import 'package:get/get.dart';
import 'package:oramemo/core/controllers/record_controller.dart';
import '../models/message.dart';
import 'chat_mock.dart';

class ChatController extends GetxController {
  final messages = <Message>[].obs;
  final isTyping = false.obs;
  int? argId=Get.arguments ?? '';

  onInit() {
    super.onInit();
    Future.delayed(Duration(milliseconds: 100), () {
      final RecordController controller = Get.find<RecordController>();
      controller.getVoiceRecordDetail(argId?.toString()??'');
      String chatMsg = controller.selectedVoiceRecord?.voiceContent ?? '';
      sendMessage(chatMsg);
    });
  }

  Future<void> sendMessage(String text) async {
    if (text.isEmpty) return;

    // Add user message
    // messages.add(Message(text: text, isUser: true));

    // Simulate AI response
    isTyping.value = true;

    final response = text;
    String currentText = '';

    // Add AI message
    final aiMessage = Message(text: currentText, isUser: false);
    messages.add(aiMessage);

    // Stream the response with improved performance
    const chunkSize = 3; // Process multiple characters at once
    for (var i = 0; i < response.length; i += chunkSize) {
      await Future.delayed(const Duration(milliseconds: 20));
      final end =
          (i + chunkSize < response.length) ? i + chunkSize : response.length;
      currentText += response.substring(i, end);
      aiMessage.text = currentText;
      messages.refresh();
    }

    isTyping.value = false;
  }
}
